package com.lishem.rpc.client.proxy;

import com.lishem.common.annotation.RpcClient;
import com.lishem.common.utils.SpringBeanFactory;
import com.lishem.rpc.client.config.RpcClientConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Set;

/**
 * 动态代理扫描管理器
 */
@Component
@Slf4j
public class ServiceProxyManager {

    /**
     * RpcClient 客户端信息配置
     */
    @Autowired
    private RpcClientConfiguration configuration;

    /**
     * 动态代理拦截处理器
     */
    @Autowired
    private ProxyHelper proxyHelper;

    /**
     * 初始化代理实现
     * 存入IOC容器中的是 接口全类名为key，代理对象是value
     */
    public void initServiceProxyInstance() {
        //1、扫描有@RpcClient注解对应的包
        Reflections reflections = new Reflections(configuration.getRpcClientApiPackage());
        // 拿到所有有@RpcClient的类
        Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(RpcClient.class);

        if (!CollectionUtils.isEmpty(typesAnnotatedWith)) {
            //获取容器对象
            DefaultListableBeanFactory beanFactory =
                    (DefaultListableBeanFactory) SpringBeanFactory.context().getAutowireCapableBeanFactory();

            for (Class<?> cls : typesAnnotatedWith) {
                //2、为每个注解创建代理
                String serviceName = cls.getName();
                Object instance = proxyHelper.newProxyInstance(cls);//创建代理

                //3、将代理对象存入到SpringIOC容器中
                beanFactory.registerSingleton(serviceName, instance);
            }
        }
    }
}